package com.mybatisflex.admin;

import com.mybatisflex.annotation.KeyType;
import com.mybatisflex.codegen.Generator;
import com.mybatisflex.codegen.config.ColumnConfig;
import com.mybatisflex.codegen.config.GlobalConfig;
import com.mybatisflex.codegen.dialect.JdbcTypeMapping;
import com.zaxxer.hikari.HikariDataSource;

public class Codegen {

    public static void main(String[] args) {

        //配置数据源
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/mybatis-flex-admin?characterEncoding=utf-8");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");

        //创建配置内容
        GlobalConfig globalConfig = new GlobalConfig();

        //设置只生成哪些表
        globalConfig.getStrategyConfig()
                .setGenerateTable("tb_account", "tb_account_session"
                , "tb_audit_message", "tb_audit_message_meta", "tb_sys_option");

        //设置表前缀
        globalConfig.setTablePrefix("tb_");


        //设置 entity 的包名
        globalConfig.setEntityGenerateEnable(true);
        globalConfig.setEntityPackage("com.mybatisflex.admin.entity");
        globalConfig.setEntityOverwriteEnable(true); //覆盖生成


        //设置主键生成器
        setPkConfigs(globalConfig);


        // Mapper 的生成配置
        globalConfig.setMapperGenerateEnable(true);
        globalConfig.setMapperPackage("com.mybatisflex.admin.mapper");


        // Service 的生成配置
        globalConfig.setServiceGenerateEnable(true);
        globalConfig.setServicePackage("com.mybatisflex.admin.service");

        // ServiceImpl 的生成配置
        globalConfig.setServiceImplGenerateEnable(true);
        globalConfig.setServiceImplPackage("com.mybatisflex.admin.service.impl");


        // Controller 的生成配置
        globalConfig.setControllerGenerateEnable(true);
        globalConfig.setControllerPackage("com.mybatisflex.admin.controller");


        // 设置时间类型为 Date
        JdbcTypeMapping.registerDateTypes();

        //通过 datasource 和 globalConfig 创建代码生成器
        Generator generator = new Generator(dataSource, globalConfig);

        //生成代码
        generator.generate();
    }


    private static void setPkConfigs(GlobalConfig globalConfig) {

        // 设置 tb_audit_message 表的主键生成器
        ColumnConfig columnConfig  = new ColumnConfig();
        columnConfig.setPrimaryKey(true);
        columnConfig.setKeyType(KeyType.Generator);
        columnConfig.setKeyValue("snowFlakeId");
        columnConfig.setColumnName("id");
        globalConfig.setColumnConfig("tb_audit_message",columnConfig);


        // 设置 tb_account_session 表的主键生成器
        ColumnConfig accountSessionKeyConfig  = new ColumnConfig();
        accountSessionKeyConfig.setPrimaryKey(true);
        accountSessionKeyConfig.setKeyType(KeyType.Generator);
        accountSessionKeyConfig.setKeyValue("uuid");
        accountSessionKeyConfig.setColumnName("id");
        globalConfig.setColumnConfig("tb_account_session",accountSessionKeyConfig);
    }
}
